<template>
  <div ref="echartDom"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose} from 'vue'
import {pxToRem} from "@/utils/index";

const props = defineProps({
  barData: {
    type: Object,
    default: () => {}
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});

const echartDom = ref(null);
const myChart = shallowRef(null);
const echarts = inject('echarts');

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let tempYAxis = []
    tempYAxis.push({
      name: '人数',
      min: 0,
      max: (value) => value.max || 100,
      nameTextStyle: {
        color: 'white',
        fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        padding: [0, 0, 0, pxToRem(-30 * props?.dialogData?.fontSizeTimes)]
      },
      nameGap: pxToRem(props?.dialogData?.fontSizeTimes === 1 ? 15 : 25),
      axisTick: {
        show: false // 不显示坐标轴刻度线
      },
      axisLine: {
        show: false, // 不显示坐标轴线
      },
      splitLine: {
        show: false // 不显示网格线
      },
      axisLabel: {
        fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        color: 'white'
      }
    })
    let option = {
      barMaxWidth: pxToRem(11 * props?.dialogData?.fontSizeTimes),
      grid: {
        left: '3%',
        right: '2%',
        bottom: '2%',
        top: `${props?.dialogData?.fontSizeTimes === 1 ? 20 : 12}%`,
        containLabel: true
      },
      dataZoom: { // 数据过多内部拖动逻辑
        type: "inside",
        zoomLock: true, // 不可缩放
        startValue: 0,
        endValue: 6,
      },
      xAxis: {
        type: 'category',
        axisTick: {
          show: false // 不显示坐标轴刻度线
        },
        axisLine: {
          show: false, // 不显示坐标轴线
        },
        splitLine: {
          show: false // 不显示网格线
        },
        axisLabel: {
          color: 'white',
          fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
          interval: 0
        },
        data: props?.barData?.xAxisData
      },
      yAxis: tempYAxis,
      series: {
        type: 'bar',
        data: props?.barData?.seriesData
      }
    }
    option && myChart.value.setOption(option, true);
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  initEchart();
};

defineExpose({
  updateChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h180 {
  height: 180px;
}
.h210 {
  height: 210px;
}
.h240 {
  height: 240px;
}
.dialog-h180 {
  width: 1120px;
  height: 500px;
}
</style>